package cn.wolfcode.p2p.interceptor;

import cn.wolfcode.p2p.base.util.RequireLogin;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //如果当前处理器 是 方法处理器的话
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            //判断方法上有没有贴到RequireLogin的注解
            if (method.getMethodAnnotation(RequireLogin.class) != null) {
                //如果有贴 看是否已经登录了
                if (UserContext.getCurrent() == null) {
                    //如果没有登录 重定向回到登录页面
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        //放行
        return true;
    }
}
